﻿using HDSmartCommunity.Models;
using HDSmartCommunity.Serial;
using MQTTnet.Client.Options;
using MQTTnet.Client;
using System.Threading.Tasks;
using System;

namespace HDSmartCommunity.BUS.MqttBUS
{
    public class SHGDLine18MqttClientBUS
    {
        IMqttClient _client;
        MqttClientOptions _options;
        public SHGDLine18MqttClientBUS()
        {
            SHGDLine18MqttClient client = SerialServer.sHGDLine18MqttClient;
            this._client = client.MqttClient;
            this._options = client.Options;
        }



        public async Task<ResponseMessage> PublicMessage(string Topic, string Message, int QuantityOfLevel)
        {
            ResponseMessage response = await PublicAsyncMessage(Topic, Message, QuantityOfLevel);
            return response;
        }
        private async Task<ResponseMessage> PublicAsyncMessage(string Topic, string Message, int QuantityOfLevel)
        {
            ResponseMessage message = new ResponseMessage() { errcode = 0, errmsg = "", data = null };
            try
            {
                if (!this._client.IsConnected)
                {
                    await this._client.ConnectAsync(_options).ConfigureAwait(false);
                }
                await this._client.PublishAsync(new MQTTnet.MqttApplicationMessage()
                {
                    Payload = System.Text.UTF8Encoding.UTF8.GetBytes(Message),
                    QualityOfServiceLevel = (MQTTnet.Protocol.MqttQualityOfServiceLevel)QuantityOfLevel,
                    Topic = Topic,
                    Retain = false
                }).ConfigureAwait(false);
            }
            catch (Exception e)
            {
                //LogHelper.Log(e.ToString());

                message.errcode = 1;
#if DEBUG
                message.errmsg = e.ToString();
#else
                message.errmsg = $"发送{Topic}主题错误";
#endif
                return message;
            }
            return message;
        }
    }
}
